package org.jeecg.modules.gis.config;

import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TokenManager {

    private final List<String> tokens;

    // serviceType -> (token -> usageCount)
    private final Map<String, Map<String, Integer>> usageMapPerService = new ConcurrentHashMap<>();

    public TokenManager(TdtTokenProperties tdtTokenProperties) {
        this.tokens = tdtTokenProperties.getTokens();
    }

    // 获取某服务类型下使用次数最少的 token
    public synchronized String getLeastUsedToken(String serviceType) {
        usageMapPerService.computeIfAbsent(serviceType, k -> {
            Map<String, Integer> map = new HashMap<>();
            for (String tk : tokens) {
                map.put(tk, 0);
            }
            return map;
        });

        Map<String, Integer> usageMap = usageMapPerService.get(serviceType);

        String leastUsedToken = usageMap.entrySet().stream()
                .min(Comparator.comparingInt(Map.Entry::getValue))
                .map(Map.Entry::getKey)
                .orElseThrow(() -> new RuntimeException("No available tokens"));

        usageMap.put(leastUsedToken, usageMap.get(leastUsedToken) + 1);

        return leastUsedToken;
    }
}
